﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Rabc.Project.Repositories;
using Rbac.Domain;
using Rbac.Project.Application.Roles.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rbac.Project.Application.Roles
{
    public class RoleService : IRoleService
    {
        private readonly IRepository<Role> repository;
        private readonly IRepository<Menu> menuRepository;
        private readonly IRepository<RoleMenu> repository1;
        private readonly IMapper mapper;

        public RoleService(IRepository<Role> repository, IRepository<Menu> menuRepository, IRepository<RoleMenu> repository1, IMapper mapper)
        {
            this.repository = repository;
            this.menuRepository = menuRepository;
            this.repository1 = repository1;
            this.mapper = mapper;
        }

        public async Task<ResultDto<Tuple<int, List<ListDto>>>> PageDataTupleAsync(int PageIndex = 1, int PageSize = 10)
        {
            var list = await repository.Queryable().OrderByDescending(m => m.CreateTime).Skip((PageIndex - 1) * PageSize).Take(PageSize).ToListAsync();


            Tuple<int, List<ListDto>> Tuple = new Tuple<int, List<ListDto>>
                (item1: list.Count(), item2: mapper.Map<List<ListDto>>(list));

            return new ResultDto<Tuple<int, List<ListDto>>> { Code = Result.Success, Data = Tuple };
        }

        public async Task<ResultDto> AssignPermissionAsync(PermissionDto dto)
        {
            var list = dto.permissionIds.Select(m => new RoleMenu {
                RoleID = dto.roleId,
                MenuID = m
            }).ToList();
            await repository1.InsertManyAsync(list);
            return new ResultDto { Code = Result.Success };
        }

        public async Task<ResultDto> InitPermission(int RoleId)
        {
            var list = (await menuRepository.QueryAsync()).Select(m => new RoleMenu { 
             RoleID = RoleId, MenuID = m.MenuId
            }).ToList();
            await repository1.InsertManyAsync(list);
            return new ResultDto { Code = Result.Success };
        }
    }
}
